<script setup>
import { useRouter } from 'vue-router'
import { deleteTcTask, getTaskDetail, updateTask } from '@/assets/api/task'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  addTaskButton: Boolean,
  loadData: Function,
  allowOperations: Boolean,
  headTitleStatus: Boolean,
})

const isNeedFold = ref(false)

defineExpose({
  openAddDialog: handleAddTask,
  isNeedFold,
})

const emit = defineEmits(['handleDrag'])

const addTaskRef = ref()

const showMessage = ref(false)

const taskData = ref({})

const taskDialogTitle = computed(() => {
  if (taskData.value.taskTitle) {
    const { projectName, itemName, taskTitle, taskCode } = taskData.value
    return `${projectName}/${itemName}/${taskTitle}-#${taskCode}`
  }
  return ''
})

const listData = ref([])

function handleMoreBtn(item) {
  let arr = []
  arr = props.data.filter((ii) => ii.itemId === item.itemId)
  item.taskList = arr[0].taskList
  item.showMoreIcon = !item.showMoreIcon
}

watch(
  () => props.headTitleStatus,
  (newVal) => {
    nextTick(() => {
      if (newVal) {
        isNeedFold.value = false
        dataFold()
      } else {
        isNeedFold.value = true
        dataExpand()
      }
    })
  },
  { deep: true, immediate: true }
)

watch(
  () => props.data,
  (newVal) => {
    nextTick(() => {
      isNeedFold.value = false
      dataFold()
    })
  },
  { deep: true }
)

const dialogVisible = ref(false)

const sourceNode = ref(null) //被拖拽的元素节点
const dragging = ref(null) //被拖拽的项

//收起数据
function dataFold() {
  listData.value = []
  let num = 0
  let numFold = 0
  let zIndexNum = 100
  //判断是否有子节点
  let isHasChild = props.data.every((item) => item.taskList.length > 0)
  props.data.forEach((item, index) => {
    if (item.taskList.length > 0) {
      if (isHasChild && index === 0) {
        numFold = 0
      } else {
        numFold++
      }
      listData.value.push({
        ...item,
        leftSpace: numFold * 320,
      })
    } else {
      num++
      zIndexNum--
      if (num > 3) {
        listData.value.push({
          ...item,
          leftSpace: 3 * 10,
          zIndexNum,
        })
      } else {
        listData.value.push({
          ...item,
          leftSpace: num * 10,
          zIndexNum,
        })
      }
    }
  })
}

//展开数据
function dataExpand() {
  // listData.value = props.data
  listData.value = []
  props.data.forEach((item, index) => {
    listData.value.push({
      ...item,
      leftSpace: index * 315,
    })
  })
}

// 拖拽中
function handleDrag(e, item) {}

// 拖拽开始
function handleDragStart(e, item) {
  //关键点 要在异步里面给被拖拽的添加上移动时效果 这样可以保证鼠标上的节点不被添加上样式
  setTimeout(() => {
    e.target.classList.add('file-item-move')
  }, 0)
  //赋值实际项
  dragging.value = item
  //赋值节点
  sourceNode.value = e.target
  emit('handleDrag', e.clientX)
}
// 拖拽进入其他项
function handleDragEnter(e, item) {
  // 为需要移动的元素设置dragstart事件
  e.dataTransfer.effectAllowed = 'move'
  if (sourceNode.value === e.target) {
    return
  }

  // 获得被拖动元素下标
  const sourceIndex = listData.value.indexOf(dragging.value)
  // 获得目标元素下标
  const targetIndex = listData.value.indexOf(item)
  if (sourceIndex < targetIndex) {
    // 插入到下个元素之后
    const firstItem = listData.value.splice(sourceIndex, 1)[0]
    listData.value.splice(targetIndex + 1, 0, firstItem)
  } else {
    // 插入到元素之前
    const firstItem = listData.value.splice(sourceIndex, 1)[0]
    listData.value.splice(targetIndex, 0, firstItem)
  }
}
//在拖拽结束时触发的事件
function handleDragEnd(e, item) {
  sourceNode.value.classList.remove('file-item-move')
}
//组织浏览器默认行为
function handleDragOver(e, item) {
  e.dataTransfer.dropEffect = 'move'
}

// 打开详情弹窗
function handleOpen(task) {
  getDetail(task.taskId)
}

function refreshDetail(taskId) {
  getDetail(taskId)
  props.loadData()
}

async function getDetail(id) {
  getTaskDetail(id).then((res) => {
    if (res.code === 200) {
      taskData.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg)
    }
  })
}

function handleDetailClose() {
  showMessage.value = false
  taskData.value = {}
}

function handleDialog(task) {
  showMessage.value = true
  handleOpen(task)
}

const addTaskVisible = ref(false)

const itemId = ref()

const projectId = ref()
const taskId = ref()

// 添加任务
// 将父任务传给创建弹窗
const parentData = ref({})
const addTaskType = ref()
function handleAddTask(data) {
  parentData.value = data
  itemId.value = data.itemId
  projectId.value = data.projectId
  taskId.value = null
  addTaskType.value = 'add'
  addTaskVisible.value = true
}

function handleAddTaskClose() {
  addTaskVisible.value = false
}

function handleUpdateTask(task, data) {
  const parent = { ...task, ...data }
  parentData.value = parent
  itemId.value = task.itemId
  projectId.value = task.projectId
  taskId.value = task.taskId
  // addTaskRef.value.setTaskForm(task)
  addTaskType.value = 'edit'
  addTaskVisible.value = true
}

async function handleReceiveTask(task) {
  task.currentStatus = 2
  const res = await updateTask(task)
  if (res.code === 200) {
    props.loadData()
    ElMessage.success('任务领取成功')
  } else {
    ElMessage.error(res.msg)
  }
}

function handleGoProject(task) {
  router.push({ path: `/chat/project/${task.projectId}` })
}

function handleDeleteTask(task) {
  deleteTcTask(task.taskId).then((res) => {
    if (res.code === 200) {
      props.loadData()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
}
</script>

<template>
  <div class="task-list">
    <div
      :draggable="false"
      @dragstart="handleDragStart($event, item)"
      @dragenter="handleDragEnter($event, item)"
      @dragend="handleDragEnd($event, item)"
      @dragover.prevent="handleDragOver($event, item)"
      v-for="(item, index) in listData"
      :key="index"
      :class="['task-item', { 'need-fold': !isNeedFold && item.taskList.length === 0 }]"
      :style="{ left: item.leftSpace + 'px', zIndex: item.zIndexNum }">
      <slot name="head" :item="item"></slot>
      <div class="task-item-content">
        <template v-if="item.taskList.length > 0">
          <template v-for="(task, taskIndex) in item.taskList" :key="taskIndex">
            <TaskItemCard
              :task="task"
              :allow-operations="props.allowOperations"
              @click="handleOpen"
              @dialogClick="handleDialog"
              @deleteTask="handleDeleteTask"
              @updateTask="(val) => handleUpdateTask(val, item)"
              @receiveTask="handleReceiveTask"
              @goProject="handleGoProject"></TaskItemCard>
            <template v-if="task.children && task.children.length > 0">
              <TaskItemCard
                v-for="(taskChild, childIndex) in task.children"
                :key="`${taskIndex}-${childIndex}`"
                :task="{ ...taskChild, parentCode: task.taskCode }"
                :allow-operations="props.allowOperations"
                @dialogClick="handleDialog"
                @deleteTask="handleDeleteTask"
                @updateTask="(val, item) => handleUpdateTask(val, item)"
                @receiveTask="handleReceiveTask"
                @goProject="handleGoProject"
                @click="handleOpen"></TaskItemCard>
            </template>
          </template>
          <div v-if="item.showMoreIcon" class="task-add look-more" @click="handleMoreBtn(item)">查看更多</div>
        </template>

        <div v-if="props.addTaskButton" class="task-add" @click="handleAddTask(item)">
          <el-icon><Plus /></el-icon>
          添加任务
        </div>
      </div>
    </div>
    <AddTask
      ref="addTaskRef"
      v-model:visible="addTaskVisible"
      :project-id="projectId"
      :item-id="itemId"
      :task-id="taskId"
      :parentData="parentData"
      :addTaskType="addTaskType"
      @close="handleAddTaskClose"
      @submitFinish="() => props.loadData && props.loadData()"></AddTask>
    <TaskChatDialog
      v-model="dialogVisible"
      width="1200px"
      class="task-dialog"
      :title="taskDialogTitle"
      body-class-name="dialog-custom"
      @close="handleDetailClose"
      destroy-on-close
      :close-on-click-modal="false">
      <TaskDetail
        :task="taskData"
        :show-message="showMessage"
        :allow-operations="props.allowOperations"
        @dialogClick="handleDialog"
        @refresh="refreshDetail"
        @receiveTask="handleReceiveTask"
        @goProject="handleGoProject"></TaskDetail>
    </TaskChatDialog>
  </div>
</template>

<style scoped lang="scss">
.task-list {
  @include use-flex();
  .task-item {
    @include use-flex(normal, normal, column);
    width: 297px;
    margin-right: 20px;
    border-radius: 8px;
    &-content {
      padding: 15px 0;
      .elp-divider {
        margin: 10px 0;
      }
    }
    .task-add {
      @include use-flex(center, center);
      .elp-icon {
        margin-right: 7px;
      }
      cursor: pointer;
      font-size: 16px;
      padding: 10px;
      border-radius: 8px;
      color: var(--elp-text-color-secondary);
      border: 2px dashed var(--elp-border-color);
      background-color: var(--elp-bg-color-page);
    }
    .look-more {
      background-color: #fff;
      margin-bottom: 10px;
    }
  }
  .need-fold {
    width: 275px;

    :deep(.group-head) {
      border: 1px solid var(--elp-border-color);
    }
  }

  /* 当被移动时的样式 */
  .file-item-move {
    background: transparent;
    color: transparent;
    border: 1px dashed #e5e5e5 !important;
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
  }

  :deep(.fiz-eim-dialog) {
    .dialog-custom {
      background-color: var(--elp-bg-color-page);
    }
  }
}
</style>
